package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.constant.RedisConstant;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.utils.RandomUtils;
import com.atguigu.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.utils.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author gcq
 * @Create 2021-04-25
 */

@RestController
@Api(tags = "短信管理")
@RequestMapping("/api/sms")
@Slf4j
public class ApiSmsController {

    @Autowired
    SmsService smsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    CoreUserInfoClient coreUserInfoClient;


    /**
     * TODO:发送验证码的时候就查询系统中是否有该用户
     * @param mobile
     * @return
     */
    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号", required = true) @PathVariable("mobile") String mobile)
    {
        // 校验手机号不为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        // 校验手机号是否合法
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        // 判断手机号是否注册
        boolean result = coreUserInfoClient.checkMobile(mobile);
        log.info("调用core-checkMobile接口，返回结果为：{}", result);
        Assert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);

        String code = RandomUtils.getFourBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        // 测试不发送短信
//        smsService.send(mobile, SmsProperties.TEMPLATE_CODE, map);

        redisTemplate.opsForValue().set(RedisConstant.SRB_SMS_CODE + mobile, code, 5, TimeUnit.MINUTES);
        return R.ok().message("短信发送成功");
    }
}